package com.atguigu.thread;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//1 高内聚低耦合的前提下，线程      操作      资源类
public class Sale2 {
    public static void main(String[] args) {

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                for (int i = 1; i <=51; i++) {
                    ticket.sale();
                }
            }
        }, "A").start();

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                for (int i = 1; i <=51; i++) {
                    ticket.sale();
                }
            }
        }, "B").start();

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                for (int i = 1; i <=51; i++) {
                    ticket.sale();
                }
            }
        }, "C").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <=51; i++) {
                    ticket.sale();
                }
            }
        }, "D").start();
    }
}
class ticket{
    public static int ticket1 = 50;
    public static Lock lock = new ReentrantLock();
    public static synchronized void sale(){
//        if(ticket1>0){
//            System.out.println("当前是"+Thread.currentThread().getName()+"卖了第"+(ticket1--)+"还剩下"+ticket1);
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
        lock.lock();
        try {
            if(ticket1>0){
                System.out.println("当前是"+Thread.currentThread().getName()+"卖了第"+(ticket1--)+"还剩下"+ticket1);
            }
        } finally {
            lock.unlock();
        }

    }
}